<template>
  <GlobalDrawer v-model="visible" title="客户详情" size="85%" :show-footer-buttons="false">
    <div v-loading="loading" class="customer-detail">
      <!-- 头部摘要信息 -->
      <el-card class="header-card" shadow="never">
        <div class="customer-header">
          <div class="header-left">
            <h2>{{ detail.name }}</h2>
            <div class="header-tags">
              <el-tag :type="getCustomerTypeColor(detail.customer_type)">
                {{ getCustomerTypeText(detail.customer_type) }}
              </el-tag>
              <el-tag v-if="detail.is_cooperation" type="success">已合作</el-tag>
              <el-tag v-else type="info">未合作</el-tag>
              <el-tag :type="getLevelTagType(detail.level)">
                {{ getLevelText(detail.level) }}
              </el-tag>
              <el-tag
                v-if="statusService.isValidMemberStatus(detail.customer_status)"
                type="warning"
              >
                会员客户
              </el-tag>
              <el-tag
                v-if="statusService.isExpiredMemberStatus(detail.customer_status)"
                type="danger"
              >
                过期会员
              </el-tag>
            </div>
          </div>
          <div class="header-actions">
            <el-button @click="handleFollowup">快速跟进</el-button>
            <el-button type="primary" @click="handleEdit">编辑客户</el-button>
          </div>
        </div>
      </el-card>

      <!-- 主体内容区域 -->
      <div class="detail-content">
        <!-- 左侧主信息 -->
        <div class="main-content">
          <!-- 1. 基础信息卡片 -->
          <el-card header="基础信息" class="section">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="客户名称">{{ detail.name || '-' }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">
                {{ detail.phone || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="负责人">
                {{ detail.user_name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="所属部门">
                {{ detail.dept_name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="客户来源">
                {{ getSourceText(detail.source) || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="客户等级">
                {{ getLevelText(detail.level) || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="重要程度">
                {{ getImportantLevelText(detail.important_level) || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="客户属性">
                {{ getCustomerAttributeText(detail.customer_attribute) || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="客户状态">
                <el-tag :type="getStatusTagType(detail.status)">
                  {{ getStatusText(detail.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 2. 企业信息卡片（仅企业客户显示） -->
          <el-card v-if="detail.customer_type === 2" header="企业信息" class="section">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="行业">
                {{ getIndustryText(detail.industry) || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="企业规模">
                {{ getScaleText(detail.scale) || '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 3. 证件信息卡片 -->
          <el-card header="证件信息" class="section">
            <el-descriptions :column="2" border>
              <!-- 企业客户显示法定代表人 -->
              <el-descriptions-item v-if="detail.customer_type === 2" label="法定代表人">
                {{ detail.legal_person || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="证件类型">
                {{ getIdTypeText(detail.id_type) || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="证件号码">
                {{ detail.id_number || '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 4. 营销信息卡片 -->
          <el-card header="营销信息" class="section">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="合作状态">
                <el-tag v-if="detail.is_cooperation" type="success">已合作</el-tag>
                <el-tag v-else type="info">未合作</el-tag>
              </el-descriptions-item>
              <el-descriptions-item v-if="detail.is_cooperation" label="合作时间">
                {{ formatTime(detail.cooperation_time) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 5. 地址信息卡片 -->
          <el-card header="地址信息" class="section">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="完整地址">
                {{ formatAddress() }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 联系人信息表格卡片 -->
          <el-card header="联系人信息" class="section">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>联系人信息</span>
                <el-button type="primary" size="small" @click="handleAddContact">
                  新增联系人
                </el-button>
              </div>
            </template>
            <el-table
              :data="detail.contacts || []"
              size="small"
              v-if="detail.contacts && detail.contacts.length > 0"
            >
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="position" label="职务" width="120" />
              <el-table-column prop="phone" label="电话" width="120" />
              <el-table-column prop="wechat" label="微信" width="120" />
              <el-table-column prop="email" label="邮箱" width="150" />
              <el-table-column prop="is_primary" label="主要联系人" width="100">
                <template #default="{ row }">
                  <el-tag v-if="row.is_primary" type="success">是</el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="创建时间" width="140" />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button type="text" size="small" @click="handleEditContact(row)">
                    编辑
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    style="color: #f56c6c"
                    @click="handleDeleteContact(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无联系人信息" :image-size="60" />
          </el-card>

          <!-- 跟进记录卡片 -->
          <el-card header="跟进记录" class="section">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>跟进记录</span>
                <el-button type="primary" size="small" @click="handleAddFollowup">
                  新增跟进
                </el-button>
              </div>
            </template>
            <el-timeline v-if="detail.followups && detail.followups.length > 0">
              <el-timeline-item
                v-for="item in detail.followups"
                :key="item.id"
                :timestamp="formatTime(item.followup_time)"
                placement="top"
              >
                <el-card>
                  <div class="followup-content">
                    <div class="followup-header">
                      <el-tag size="small">{{ getFollowupTypeText(item.followup_type) }}</el-tag>
                    </div>
                    <p class="followup-desc">{{ item.content }}</p>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
            <el-empty v-else description="暂无跟进记录" :image-size="60" />
          </el-card>

          <!-- 订单信息卡片 -->
          <el-card header="订单信息" class="section">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>订单信息</span>
                <el-button type="primary" size="small" @click="handleAddOrder">新增订单</el-button>
              </div>
            </template>
            <el-table
              :data="detail.orders || []"
              size="small"
              v-if="detail.orders && detail.orders.length > 0"
            >
              <el-table-column prop="order_no" label="订单编号" width="150" />
              <el-table-column prop="order_type" label="订单类型" width="120">
                <template #default="{ row }">
                  {{ getOrderTypeText(row.order_type) }}
                </template>
              </el-table-column>
              <el-table-column prop="total_amount" label="订单金额" width="120">
                <template #default="{ row }">¥{{ row.total_amount }}</template>
              </el-table-column>
              <el-table-column prop="payment_status" label="付款状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getPaymentStatusTagType(row.payment_status)">
                    {{ getPaymentStatusText(row.payment_status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="create_time" label="创建时间" width="140" />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button type="text" size="small" @click="handleViewOrder(row)">查看</el-button>
                  <el-button type="text" size="small" @click="handleEditOrder(row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无订单信息" :image-size="60" />
          </el-card>
        </div>

        <!-- 右侧侧边栏 -->
        <div class="sidebar">
          <!-- 统计信息卡片 -->
          <StatisticsCard :data="detail" />

          <!-- 会员信息卡片（会员客户时显示） -->
          <el-card
            v-if="statusService.isMemberStatus(detail.customer_status)"
            header="会员信息"
            class="section"
          >
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="会员类型">
                {{ getMemberTypeText(detail.member_type) }}
              </el-descriptions-item>
              <el-descriptions-item label="服务期限">
                {{ formatTime(detail.member_start_time) }} 至
                {{ formatTime(detail.member_end_time) }}
              </el-descriptions-item>
              <el-descriptions-item label="账号类型">
                {{ detail.is_main_account === 1 ? '主账号' : '子账号' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 标签与备注卡片 -->
          <TagsAndRemarkCard :data="detail" />
        </div>
      </div>
    </div>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { customerApi } from '@/api/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'
  import StatisticsCard from './customer_form/StatisticsCard.vue'
  import TagsAndRemarkCard from './customer_form/TagsAndRemarkCard.vue'
  import request from '@/utils/request'
  import { statusService } from '@/utils/statusService'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    customerId: {
      type: Number,
      default: 0,
    },
  })

  const emit = defineEmits([
    'update:modelValue',
    'edit',
    'add-contact',
    'edit-contact',
    'add-followup',
    'add-order',
  ])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const loading = ref(false)
  const detail = ref<any>({})

  // 选项数据
  const sourceOptions = ref<Array<{ value: string; label: string }>>([])
  const industryOptions = ref<Array<{ value: string; label: string }>>([])
  const scaleOptions = ref<Array<{ value: string; label: string }>>([])

  // 加载选项数据
  const loadOptions = async () => {
    try {
      // 加载客户来源选项
      const sourceRes = await customerApi.sourceOptions()
      sourceOptions.value = sourceRes.data || []

      // 加载行业选项
      const industryRes = await customerApi.industryOptions()
      industryOptions.value = industryRes.data || []

      // 加载规模选项
      const scaleRes = await customerApi.scaleOptions()
      scaleOptions.value = scaleRes.data || []
    } catch (error: any) {
      // 忽略请求取消错误（组件卸载时的正常行为）
      if (error?.code === 'ERR_CANCELED') {
        return
      }
      console.error('加载选项数据失败:', error)
    }
  }

  // 获取客户详情
  const getCustomerDetail = async () => {
    if (!props.customerId) return

    loading.value = true
    try {
      const res = await customerApi.detail(props.customerId)
      if (res.data) {
        detail.value = res.data
      }
    } catch (error: any) {
      if (error?.code !== 'ERR_CANCELED') {
        console.error('获取客户详情失败:', error)
        ElMessage.error('获取客户详情失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 格式化地址
  const formatAddress = () => {
    const { province_name, city_name, district_name, address } = detail.value
    return (
      `${province_name || ''}${city_name || ''}${district_name || ''}${address || ''}`.trim() || '-'
    )
  }

  // 格式化时间
  const formatTime = (timestamp: number) => {
    if (!timestamp) return '-'
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  // 获取客户类型
  const getCustomerTypeText = (type: number) => {
    const map: Record<number, string> = { 1: '个人客户', 2: '企业客户' }
    return map[type] || '-'
  }

  const getCustomerTypeColor = (type: number) => {
    const map: Record<number, string> = { 1: 'info', 2: 'primary' }
    return map[type] || 'info'
  }

  // 获取客户等级
  const getLevelText = (level: number) => {
    const map: Record<number, string> = { 1: '普通客户', 2: '重要客户', 3: '核心客户' }
    return map[level] || '-'
  }

  const getLevelTagType = (level: number) => {
    const map: Record<number, string> = { 1: 'info', 2: 'warning', 3: 'danger' }
    return map[level] || 'info'
  }

  // 获取客户状态
  const getStatusText = (status: number) => {
    const map: Record<number, string> = {
      1: '潜在客户',
      2: '跟进中',
      3: '已合作',
      4: '公海客户',
      5: '已流失',
    }
    return map[status] || '-'
  }

  const getStatusTagType = (status: number) => {
    const map: Record<number, string> = {
      1: 'info',
      2: 'warning',
      3: 'success',
      4: 'primary',
      5: 'danger',
    }
    return map[status] || 'info'
  }

  // 获取行业类型（从API加载的选项数据中查找）
  const getIndustryText = (industry: string) => {
    if (!industry) return '-'
    const option = industryOptions.value.find(item => String(item.value) === String(industry))
    return option ? option.label : industry
  }

  // 获取客户来源（从API加载的选项数据中查找）
  const getSourceText = (source: string) => {
    if (!source) return '-'
    const option = sourceOptions.value.find(item => String(item.value) === String(source))
    return option ? option.label : source
  }

  // 获取重要程度
  const getImportantLevelText = (level: number) => {
    const map: Record<number, string> = { 1: '普通', 2: '重要', 3: '关键' }
    return map[level] || '-'
  }

  // 获取证件类型
  const getIdTypeText = (type: number) => {
    const map: Record<number, string> = { 1: '身份证', 2: '统一社会信用代码', 3: '营业执照号' }
    return map[type] || '-'
  }

  // 获取客户属性
  const getCustomerAttributeText = (attribute: number) => {
    const map: Record<number, string> = { 1: '普通', 2: '合作', 3: '会员' }
    return map[attribute] || '-'
  }

  // 获取企业规模（从API加载的选项数据中查找）
  const getScaleText = (scale: string) => {
    if (!scale) return '-'
    const option = scaleOptions.value.find(item => String(item.value) === String(scale))
    return option ? option.label : scale
  }

  // 获取会员类型
  const getMemberTypeText = (type: number) => {
    const map: Record<number, string> = { 1: '普惠版', 2: '标准版', 3: 'VIP版' }
    return map[type] || '-'
  }

  // 获取跟进类型
  const getFollowupTypeText = (type: number) => {
    const map: Record<number, string> = { 1: '电话', 2: '微信', 3: '邮件', 4: '上门', 5: '会议' }
    return map[type] || '-'
  }

  // 获取订单类型
  const getOrderTypeText = (type: number) => {
    const map: Record<number, string> = {
      1: '诉讼业务',
      2: '非诉业务',
      3: '咨询服务',
      4: '其他业务',
    }
    return map[type] || '-'
  }

  // 获取付款状态
  const getPaymentStatusText = (status: number) => {
    const map: Record<number, string> = { 1: '待付款', 2: '部分付款', 3: '已付款' }
    return map[status] || '-'
  }

  const getPaymentStatusTagType = (status: number) => {
    const map: Record<number, string> = { 1: 'danger', 2: 'warning', 3: 'success' }
    return map[status] || 'info'
  }

  // 事件处理
  const handleEdit = () => {
    emit('edit', props.customerId)
  }

  const handleFollowup = () => {
    emit('add-followup', props.customerId)
  }

  const handleAddContact = () => {
    emit('add-contact', props.customerId)
  }

  const handleEditContact = (row: any) => {
    emit('edit-contact', row.id)
  }

  const handleDeleteContact = async (row: any) => {
    try {
      await ElMessageBox.confirm('确定要删除该联系人吗？', '提示', {
        type: 'warning',
      })
      ElMessage.success('删除成功')
      getCustomerDetail()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除联系人失败:', error)
      }
    }
  }

  const handleAddFollowup = () => {
    emit('add-followup', props.customerId)
  }

  const handleAddOrder = () => {
    emit('add-order', props.customerId)
  }

  const handleViewOrder = (row: any) => {
    // 查看订单详情
    console.log('查看订单', row)
  }

  const handleEditOrder = (row: any) => {
    // 编辑订单
    console.log('编辑订单', row)
  }

  // 监听抽屉打开和客户ID变化
  watch(
    [visible, () => props.customerId],
    ([isVisible, customerId]) => {
      if (isVisible && customerId) {
        // 加载选项数据
        loadOptions()
        // 获取客户详情
        getCustomerDetail()
      }
    },
    { immediate: false }
  )
</script>

<style scoped>
  .customer-detail {
    padding-bottom: 20px;
  }

  .header-card {
    margin-bottom: 20px;
  }

  .customer-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .header-left h2 {
    margin: 0 0 12px 0;
    font-size: 20px;
    font-weight: 600;
  }

  .header-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }

  .detail-content {
    display: flex;
    gap: 20px;
  }

  .main-content {
    flex: 1;
    min-width: 0; /* 防止flex子项溢出 */
  }

  .sidebar {
    width: 350px;
    flex-shrink: 0; /* 防止收缩 */
  }

  /* 响应式设计 - 当屏幕宽度 < 1200px 时，侧边栏放下方 */
  @media (max-width: 1200px) {
    .detail-content {
      flex-direction: column;
    }

    .sidebar {
      width: 100%;
    }
  }

  /* 超小屏幕优化 - 当屏幕宽度 < 768px 时 */
  @media (max-width: 768px) {
    .detail-content {
      gap: 10px;
    }

    .customer-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }

    .header-actions {
      width: 100%;
      justify-content: flex-start;
    }

    .header-actions .el-button {
      flex: 1;
    }
  }

  .section {
    margin-bottom: 20px;
  }

  .followup-content {
    padding: 8px 0;
  }

  .followup-header {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
  }

  .followup-desc {
    margin: 0;
    color: #606266;
    line-height: 1.6;
  }
</style>
